<template>
  <div class="ma-content-block">
    <!-- Tab 栏 jia-->
<!--    <a-tabs v-model="activeTab" @change="handleTabChange" v-if="false">
      <a-tab-pane key="zh" title="中文"></a-tab-pane>
      <a-tab-pane key="en" title="英文"></a-tab-pane>
      <a-tab-pane key="ja" title="日语"></a-tab-pane>
      <a-tab-pane key="ko" title="韩语"></a-tab-pane>
    </a-tabs> -->

    <sa-table ref="crudRef" :options="options" :columns="columns" :searchForm="searchForm">
      <!-- 搜索区 tableSearch -->
      <template #tableSearch>
<!--        <a-col :span="8">-->
<!--          <a-form-item label="招聘企业" field="recruitment_enterprise">-->
<!--            <a-input v-model="searchForm.recruitment_enterprise" placeholder="请输入招聘企业" />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
 <a-col :span="8">
        <a-form-item label="招聘企业" field="enterprise_id">
          <a-select
              v-model="searchForm.enterprise_id"
              :options="enterpriseId"
              allow-clear
              placeholder="请选择招聘企业" />
        </a-form-item>
		     </a-col>
        <a-col :span="8">
          <a-form-item label="工作省" field="province_id">
            <a-select
              v-model="searchForm.province_id"
              :options="provinceOptions"
              allow-clear
              placeholder="请选择工作省"
              @change="handleProvinceChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="工作城市" field="city_id">
            <a-select
              v-model="searchForm.city_id"
              :options="cityOptions"
              allow-clear
              placeholder="请选择工作城市"
              :disabled="!searchForm.province_id"
              @change="handleCityChange"
            />
          </a-form-item>
        </a-col>
		<a-col :span="8">
			<a-form-item label="工作区域" field="district_id">
			  <a-select
			    v-model="searchForm.district_id"
			    :options="districtOptions"
			    allow-clear
			    placeholder="请选择工作区"
			    :disabled="!searchForm.city_id"
			  />
			</a-form-item>
		</a-col>
        <a-col :span="8">
          <a-form-item label="职位名称" field="position_name">
            <a-input v-model="searchForm.position_name" placeholder="请输入职位名称" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="展示/下架" field="is_display">
            <sa-select v-model="searchForm.is_display" dict="yes_or_no" placeholder="请选择是否展示/下架" allow-clear />
          </a-form-item>
        </a-col>
      </template>
	  <template #is_display="{ record }">
	    <sa-switch v-model="record.is_display" checkedText="是"  uncheckedText="否" @change="changeStatus($event, record.recruitment_id)"></sa-switch>
	  </template>
	   <template #sort_order="{ record }">
	          <a-input-number 
	            v-model="record.sort_order"
	            :min="0"
	            style="width: 80px"
	            @change="changeSortOrder(record.video_id, record.sort_order)"
	          />
	  </template>

      <!-- Table 自定义渲染 -->
    </sa-table>

    <!-- 编辑表单 -->
    <edit-form ref="editRef" @success="refresh" />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import EditForm from './edit.vue'
import api from '../api/recruitment'
import commonApi from '@/api/common'
// 引用定义
const crudRef = ref()
const editRef = ref()
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const enterpriseId=ref([])

// 搜索表单
const searchForm = ref({
  recruitment_enterprise: '',
 province_id: '',
 city_id: '',
 area_id: '',
  position_name: '',
  is_display: '',
  lang_code:''
})


// SaTable 基础配置
const options = reactive({
  api: api.getPageList,
  pk: 'recruitment_id',
  rowSelection: { showCheckedAll: true },
  add: {
    show: true,
    auth: ['/recruitment/recruitment/save'],
    func: async (params) => {
      const currentLangCode = searchForm.value.lang_code;
      editRef.value?.open()
      editRef.value?.setFormData({lang_code:currentLangCode})
    },
  },
  edit: {
    show: true,
    auth: ['/recruitment/recruitment/update'],
    func: async (record) => {
      editRef.value?.open('edit')
      editRef.value?.setFormData(record)
    },
  },
  delete: {
    show: true,
    auth: ['/recruitment/recruitment/destroy'],
    func: async (params) => {
      const resp = await api.delete(params)
      if (resp.code === 200) {
        Message.success(`删除成功！`)
        crudRef.value?.refresh()
      }
    },
  },
  export: { show: true, url: '/recruitment/recruitment/export', auth: ['/recruitment/recruitment/export'] },
})

// SaTable 列配置
const columns = reactive([
  {
     title: '排序序号', 
     dataIndex: 'sort_order', 
     width: 180,
     slots: { customRender: 'sort_order' } // 新增插槽配置
   },
  { title: '职位名称', dataIndex: 'position_name', width: 180 },
  { title: '招聘企业', dataIndex: 'enterprise_id_text', width: 180 },
  { title: '工作省', dataIndex: 'province_id_text', width: 180 },
  { title: '工作市', dataIndex: 'city_id_text', width: 180 },
  { title: '工作区', dataIndex: 'district_id_text', width: 180 },
  { title: '薪资范围', dataIndex: 'salary_range_text', width: 180 },
  { title: '工作经验年限', dataIndex: 'work_experience_text', width: 180 },
  { title: '发布日期', dataIndex: 'release_date', width: 180 },
  { title: '招聘人数', dataIndex: 'recruitment_number', width: 180 },
  { title: '学历要求', dataIndex: 'education_requirement_text', width: 180 },
  { title: '是否展示', dataIndex: 'is_display',  width: 180  }
])

// 页面数据初始化
const initPage = async () => {
  searchForm.value.lang_code='zh'
  // 若有省市区数据，重新加载对应数据
  await loadProvinces()
  // 若有省市区数据，重新加载对应数据
  if (searchForm.value.province_id!=='') {
    await loadCities(earchForm.value.province_id)
    if (earchForm.value.city_id!=='') {
      await loadDistricts(searchForm.value.city_id)
    }

}
//jia
const handleTabChange = async (key) => {
  // 设置语言代码
  searchForm.value.lang_code = key
	// 刷新表格数据
	crudRef.value?.refresh()
}

  const enterpriseIdData= await commonApi.commonGet('/recruitmentEnterprise/recruitmentEnterprise/getSelect',{lang_code:searchForm.value.lang_code})
  enterpriseId.value = enterpriseIdData.data
}
// SaTable 数据请求
const refresh = async () => {
  crudRef.value?.refresh()
}
//jia
const changeSortOrder = async (id,sortOrder) => {
  try {
    const response = await api.updateSortOrder({
      id: id,
      sort_order: sortOrder
    });
    if (response.code === 200) {
      Message.success('排序修改成功');
      crudRef.value?.refresh();
    } else {
      Message.error('排序修改失败');
    }
  } catch (error) {
    console.log(error,"error")
    Message.error('排序修改失败1');
  }
}
const changeStatus = async (is_display, id) => {
  const response = await api.changeStatus({ id, is_display})
  if (response.code === 200) {
    Message.success(response.message)
    crudRef.value.refresh()
  }
}
const loadProvinces = async () => {
	
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect',{level:1}) // 替换为实际获取省份的 API 地址
  provinceOptions.value = resp.data.map(item => ({
    value: item.value,
    label: item.label
  }))
  searchForm.value.city_id = ''
  searchForm.value.district_id = ''
}

// 加载城市数据
const loadCities = async (provinceId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', {level:2,parent_code:provinceId }) // 替换为实际获取城市的 API 地址
  cityOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  // 清空市选择后，同时清空区选择
  searchForm.value.district_id = ''
  // districtOptions.value = []
}


// 加载区县数据
const loadDistricts = async (cityId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', { level:3,parent_code:cityId }) // 替换为实际获取区县的 API 地址
  districtOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
   searchForm.value.district_id = ''
}

// 省选择变化处理
const handleProvinceChange = async (provinceId) => {
  if (provinceId) {
    await loadCities(provinceId)
  } else {
   
    searchForm.value.city_id = ''
    searchForm.value.district_id = ''
  }
}

// 市选择变化处理
const handleCityChange = async (cityId) => {
  if (cityId) {
    await loadDistricts(cityId)
  } else {
    searchForm.value.district_id = ''
  }
}

// 页面加载完成执行
onMounted(async () => {
  initPage()
  refresh()
})
</script>
